// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-30

package session

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/http/logics/detail"
	"server/app/http/models"
	"server/app/http/responses"
	"server/app/lib/authorizer"
)

// Logic
// 加载场次.
type Logic struct {
	detail.Logic

	auth     *authorizer.Authentication
	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: NewResponse(),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	for _, fn := range []func(context.Context) error{
		o.ParseSession,
		o.ParseGoods,
		o.ParseTicket,
		o.ParsePond,
		o.ParseArcade,
	} {
		if err = fn(ctx); err != nil {
			return res.WithError(err)
		}
	}
	return res.With(o.response)
}

func (o *Logic) ParseArcade(ctx context.Context) (err error) {
	var arcade *models.Arcades
	if arcade, err = o.GetArcade(ctx, o.response.Ticket.ArcadeId); err == nil {
		o.response.WithArcade(arcade)
	}
	return
}

func (o *Logic) ParseGoods(ctx context.Context) (err error) {
	var gs []*responses.TicketFreeGoodsResponse
	if gs, err = o.ListFreeGoodsResponse(ctx, o.response.Session.Id); err != nil {
		return
	}
	if len(gs) > 0 {
		o.response.Session.AddGoodsResponse(gs...)
	}
	return
}

func (o *Logic) ParsePond(ctx context.Context) (err error) {
	var pond *models.ArcadePond
	if pond, err = o.GetPond(ctx, o.response.Ticket.PondId); err == nil {
		o.response.Ticket.WithPond(pond)
	}
	return
}

func (o *Logic) ParseSession(ctx context.Context) (err error) {
	var m *models.TicketSession
	if m, err = o.GetSession(ctx, o.request.Id); err == nil {
		o.response.WithSession(m)
	}
	return
}

func (o *Logic) ParseTicket(ctx context.Context) (err error) {
	var ticket *models.Ticket
	if ticket, err = o.GetTicket(ctx, o.response.Session.TicketId); err == nil {
		o.response.WithTicket(ticket)
	}
	return
}
